<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link
      href="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.2/leaflet.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.2/leaflet.js"></script>
    <!-- 引入leaflet-draw -->
    <script src="./js/leaflet-draw/dist/leaflet.draw-src.js"></script>
    <link rel="stylesheet" href="./js/leaflet-draw/dist/leaflet.draw-src.css" />

    <script src="./js/leaflet-lasso.umd.js"></script>

    <!-- 引入leaflet-measure-path -->
    <link rel="stylesheet" href="./js/leaflet-measure-path.css" />
    <script src="./js/leaflet-measure-path.js"></script>
    <script src="js/leaflet-tilelayer-wmts.js"></script>

    <script src="./js/Leaflet.Editable.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.js"></script>
    <script
      src="js/v2.6.10/vue.js"
      type="text/javascript"
      charset="utf-8"
    ></script>
    <!-- 引入样式 -->
    <link
      rel="stylesheet"
      href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
    />
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
      }

      * {
        margin: 0px;
        padding: 0px;
      }

      #pdbmap {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>

  <body>
    <div id="pdbmap">
      <!-- 底图 -->
      <div
        class="map_box"
        id="dituContent"
        style="width: 100%; height: 100%"
      ></div>
      <!-- 地图切换 -->
      <div class="map-change">
        <div class="map-item" v-for="(item,index) in mapUrl" :key="index">
          <div
            style="display: flex; flex-direction: column"
            @click="changemap(item.type)"
          >
            <img
              style="width: 75px; height: 75px; border-radius: 6px"
              :src="item.imghare"
            />
          </div>
          <div class="map-type">{{item.tite}}</div>
        </div>
      </div>
      <!-- 地图工具 -->
      <div class="self-tools">
        <a class="delete-tools" @click="stopDraw()">
          <span class="sr-only">删除</span>
        </a>
      </div>
      <div
        style="
          position: absolute;
          bottom: 10px;
          left: 10px;
          z-index: 99999999999;
          width: 50%;
        "
      >
        <div style="display: flex; justify-content: space-between; width: 100%">
          <el-button
            size="small"
            type="primary"
            plain
            @click="startTagging(1)"
            v-if="!callType"
            >开始标注</el-button
          >
          <el-button
            size="small"
            type="primary"
            plain
            @click="startTagging(1)"
            v-if="callType"
            >重新标注</el-button
          >
          <el-button size="small" type="primary" plain @click="startTagging(0)"
            >清除标注</el-button
          >
          <el-button size="small" type="primary" plain @click="selectGeoJson"
            >确定选点</el-button
          >
          <el-button size="small" type="primary" plain @click="sendMess"
            >保存并关闭</el-button
          >
        </div>
      </div>
    </div>
  </body>
  <script>
    const urlMap = "https://map.pipechina.com.cn/wmts";
    new Vue({
      el: "#pdbmap",
      data() {
        return {
          map: null,
          // 图层组
          highs: null,
          // 绘制线的所有点
          pointnods: [],
          pointISLine: false, //false点，true 线
          zoomList: [
            20000000, 1000000, 500000, 200000, 100000, 50000, 20000, 10000,
            5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 1,
          ],
          // 获取点击的坐标
          dataLngLat: [],
          tPipeLineId: "",
          mapUrl: [
            {
              tite: "矢量图",
              // url: "http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=fb258b4c0bbf60ff7a0205b519ad9a96",
              imghare: "./img/vec.jpg",
              Subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
              minimumLevel: 4,
              maximumLevel: 18,
              layerobj: {},
              index: 0,
              type: "vec",
            },
            {
              tite: "影像图",
              // url: "http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=fb258b4c0bbf60ff7a0205b519ad9a96",
              imghare: "./img/img.jpg",
              Subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
              minimumLevel: 4,
              maximumLevel: 18,
              layerobj: {},
              index: 0,
              type: "img",
            },
            {
              tite: "地形图",
              // url: "http://t0.tianditu.gov.cn/DataServer?T=ter_c&x={x}&y={y}&l={z}&tk=fb258b4c0bbf60ff7a0205b519ad9a96",
              imghare: "./img/ter.jpg",
              Subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
              minimumLevel: 4,
              maximumLevel: 18,
              layerobj: {},
              index: 0,
              type: "ter",
            },
          ],
          mapSelectClick: false, //判断是否开始标注
          drawLayerGrounp: null,
          drawControl: null,
          highlight: null,
          formDataObj: null,
          contentData: null,
          callType: null, //false新增调用 true 修改调用
          editId: "", //回显数据id
          tableName: "", //回显数据表名
          showWeight: 20, //宽度
          showColor: "#ffff00", //颜色
          wmtsMap: null,
        };
      },
      methods: {
        // 定位几何
        toLocation() {
          const formData = new FormData();
          formData.append("tableName", this.tableName);
          formData.append("dataId", this.editId);
          axios({
            // 请求方式
            method: "POST",
            // 请求地址
            url: "https://test-imspipeline.pipechina.com.cn:6080/sjgl-webhd/tableInfo/getGeoJsonById",
            // url: "http://10.37.99.129:8088/tableInfo/getGeoJsonById",
            // URL中的查询参数
            data: formData,
          }).then((res) => {
            if (res.data.code == 10000) {
              if (this.callType) {
                let geojson = JSON.parse(res.data.data[0].geojson);
                const _formData = new FormData();
                _formData.append("slng", geojson.coordinates[0][0][0]);
                _formData.append("slat", geojson.coordinates[0][0][1]);
                _formData.append(
                  "elng",
                  geojson.coordinates[0][geojson.coordinates[0].length - 1][0]
                );
                _formData.append(
                  "elat",
                  geojson.coordinates[0][geojson.coordinates[0].length - 1][1]
                );
                _formData.append("buffer", "10");
                _formData.append("pipeLineId", this.tPipeLineId);
                axios({
                  // 请求方式
                  method: "POST",
                  // 请求地址
                  url: "https://test-imspipeline.pipechina.com.cn:6080/sjgl-webhd/onlinedata/queryGeoJsonByPoint",
                  // url: "http://10.37.99.129:8088/onlinedata/queryGeoJsonByPoint",
                  // URL中的查询参数
                  data: _formData,
                }).then((res) => {
                  if (res.data.code == 10000) {
                    this.contentData = res.data.data;
                  } else {
                    this.$message.error("查询失败");
                  }
                });
                var layerGeo = L.geoJSON(geojson, {
                  style: {
                    color: this.showColor,
                    weight: this.showWeight,
                    opacity: 0.5,
                  },
                }).addTo(this.highs);
                this.map.fitBounds(layerGeo.getBounds());
              } else {
                let geojson = JSON.parse(res.data.data[0].geojson);
                var layerGeo = L.geoJSON(geojson, {
                  style: {
                    color: "#ffff00",
                    weight: 10,
                    opacity: 0,
                  },
                }).addTo(this.drawLayerGrounp);
                this.map.fitBounds(layerGeo.getBounds());
              }
            } else {
              this.$message.error("查询失败");
            }
          });
        },
        // 开始标注
        startTagging(e) {
          this.pointnods = [];
          this.dataLngLat = [];
          if (e == 1) {
            this.mapSelectClick = true;
          } else {
            this.mapSelectClick = false;
          }
          this.highs.clearLayers();
          this.stopDraw();
        },
        // 确定选点
        selectGeoJson() {
          let formData = this.formDataObj;
          let that = this;
          axios({
            // 请求方式
            method: "POST",
            // 请求地址
            url: "https://test-imspipeline.pipechina.com.cn:6080/sjgl-webhd/onlinedata/queryGeoJsonByPoint",
            // url: "http://10.37.99.129:8088/onlinedata/queryGeoJsonByPoint",
            // URL中的查询参数
            data: formData,
          }).then((res) => {
            if (res.data.code == 10000) {
              this.contentData = res.data.data;
              let _Ddata = res.data.data;
              let mileage = _Ddata.startM;
              let lineId = _Ddata.lineId;
              that.highs.clearLayers();
              // 添加在线点 移除当前高亮

              let point = L.geoJSON(JSON.parse(_Ddata.geoJson), {
                style: {
                  color: this.showColor,
                  weight: this.showWeight,
                  opacity: 0.5,
                },
              }).addTo(this.highs);
              this.pointnods = [];
              that.dataLngLat = [];
            } else {
              this.$message.error("查询失败");
            }
          });
        },
        onLoad() {
          let that = this;
          this.map = L.map("dituContent", {
            center: [33.84371698169494, 108.77701128694328],
            zoom: 5,
            zoomControl: false,
            attributionControl: false,
          }); //默认显示16层级，设置默认加载中心点经纬度
          this.highsLary = new L.FeatureGroup();
          this.map.addLayer(this.highsLary);
          this.highs = new L.FeatureGroup();
          this.map.addLayer(this.highs);
          var wmtsOptionsMap = {
            type: "wmts",
            layer: "img",
            format: "tiles",
            style: "default",
            tilematrixset: "w",
            wrapX: false,
            version: "1.0.0",
            request: "GetTile",
          };
          this.wmtsMap = new L.TileLayer.WMTS(urlMap, wmtsOptionsMap);
          this.map.addLayer(this.wmtsMap);
          this.wmtsMap.bringToBack();
          this.map.on("click ", (e) => {
            if (!this.mapSelectClick) {
              return;
            }

            let marker = e;
            let zoom = this.map.getZoom(); //获取缩放级别
            let latlng = marker.latlng;
            if (!this.pointISLine) {
              if (this.dataLngLat.length == 1) {
                this.$message.error("只能标注1个点");
                return;
              }
              this.dataLngLat = [
                {
                  lng: latlng.lng,
                  lat: latlng.lat,
                },
              ];
              let _diandata = {
                slng: latlng.lng,
                slat: latlng.lat,
                buffer: this.zoomList[zoom],
                pipeLineId: this.tPipeLineId,
              };
              // 显示点
              this.pointnods.push(
                L.circleMarker(e.latlng, {
                  color: "#ff0000",
                  fillColor: "#ffffff",
                  fillOpacity: 1,
                  radius: 5,
                }).addTo(this.highs)
              );
              const formData = new FormData();
              formData.append("slng", latlng.lng);
              formData.append("slat", latlng.lat);
              formData.append("buffer", this.zoomList[zoom]);
              formData.append("pipeLineId", this.tPipeLineId);
              this.formDataObj = formData;
            } else {
              if (that.dataLngLat.length == 0) {
                that.dataLngLat = [
                  {
                    lng: latlng.lng,
                    lat: latlng.lat,
                  },
                ];
                // 显示点
                this.pointnods.push(
                  L.circleMarker(e.latlng, {
                    color: "#ff0000",
                    fillColor: "#ffffff",
                    fillOpacity: 1,
                    radius: 5,
                  }).addTo(this.highs)
                );
                return;
              }
              if (that.dataLngLat.length == 1) {
                that.dataLngLat.push({
                  lng: latlng.lng,
                  lat: latlng.lat,
                });
                let _diandata = {
                  slng: that.dataLngLat[0].lng,
                  slat: that.dataLngLat[0].lat,
                  elng: that.dataLngLat[1].lng,
                  elat: that.dataLngLat[1].lat,
                  buffer: this.zoomList[zoom],
                  pipeLineId: this.tPipeLineId,
                };
                const formData = new FormData();
                formData.append("slng", that.dataLngLat[0].lng);
                formData.append("slat", that.dataLngLat[0].lat);
                formData.append("elng", that.dataLngLat[1].lng);
                formData.append("elat", that.dataLngLat[1].lat);
                formData.append("buffer", this.zoomList[zoom]);
                formData.append("pipeLineId", this.tPipeLineId);
                this.formDataObj = formData;
                // 显示点
                this.pointnods.push(
                  L.circleMarker(e.latlng, {
                    color: "#ff0000",
                    fillColor: "#ffffff",
                    fillOpacity: 1,
                    radius: 5,
                  }).addTo(this.highs)
                );
              } else {
                this.$message.error("只能标注2个点");
              }
            }
          });
        },
        addWmsLayer(layers, url) {
          var wmsLayer = new L.tileLayer.wms(url, {
            layers: layers, //需要加载的图层
            format: "image/png", //返回的数据格式
            transparent: true,
            version: "1.1.1",
            CQL_FILTER: "id in ('" + this.tPipeLineId + "')",
          });
          this.map.addLayer(wmsLayer);
        },
        sendMess() {
          let e = this.contentData;
          window.parent.postMessage(
            {
              status: "ok",
              params: e,
            },
            "*"
          );
        },
        // 地图切换
        changemap(data) {
          this.map.removeLayer(this.wmtsMap);
          var wmtsOptionsMap = {
            type: "wmts",
            layer: data,
            format: "tiles",
            style: "default",
            tilematrixset: "w",
            wrapX: false,
            version: "1.0.0",
            request: "GetTile",
            // tilematrixset: "w",
            // matrixIds: matrixIds,//可缩放
          };
          this.wmtsMap = new L.TileLayer.WMTS(urlMap, wmtsOptionsMap);
          this.map.addLayer(this.wmtsMap);
          this.wmtsMap.bringToBack();
        },
        // 初始化绘制控件
        initDrawCtrl() {
          this.drawLayerGrounp = L.featureGroup().addTo(this.map);
          //初始化绘制控件
          this.drawControl = new L.Control.Draw({
            position: "topright", //控件位置 'topleft'(默认), 'topright', 'bottomleft' or 'bottomright'
            draw: {
              polyline: true,
              polygon: true,
              rectangle: true,
              circle: true,
              marker: true,
              circlemarker: false,
            },
          }).addTo(this.map);
          // 添加绘制完监听事件
          this.map.on(L.Draw.Event.CREATED, this.drawCreatedBack);
          this.map.on(L.Draw.Event.DELETED, this.drawDeletedBack);
          // this.map.on('dblclick', this.onDoubleClick);
          this.map.on("moveend", this.showMapInfo);
        },
        // 交互绘制回调
        drawCreatedBack(e) {
          let drawLayer = e.layer;
          // 绘制的图形图层对象
          const { layer, layerType } = e;
          if (layerType === "polygon") {
            //layer.getLatLngs()得到的多边形的经纬度集合，多边形得到的是一个二维数组，这里要取里面的数组，一定要注意
            let latlng = layer.getLatLngs()[0];
            console.log(latlng);
            //一个自定义的计算面积的函数
            let area = this.formatArea(latlng);
            var polygon = L.polygon([latlng])
              .addTo(this.drawLayerGrounp)
              .showMeasurements();
            // this.onDoubleClick(latlng[1], area)
          } else if (layerType === "polyline") {
            //polyline得到的是一个一维数组，直接使用
            let latlng = layer.getLatLngs();
            //一个自定义的计算长度的函数
            let distance = this.formatLength(latlng);
            var polygon = L.polyline([latlng])
              .addTo(this.drawLayerGrounp)
              .showMeasurements();
            // this.onDoubleClick(latlng[1], distance)
          }

          if (!this.drawLayerGrounp) {
            //图层组
            this.drawLayerGrounp = new L.FeatureGroup();
            // 添加
            this.map.addLayer(this.drawLayerGrounp);
          }
          // 添加到图层组
          this.drawLayerGrounp.addLayer(drawLayer);
        },
        // 获取面积
        formatArea(polygon) {
          //L.GeometryUtil.geodesicArea(),返回number类型的数据，单位是平方米，这里做了一下转化
          var seeArea = L.GeometryUtil.geodesicArea(polygon);
          let area = (seeArea / 10e5).toFixed(2) + "k㎡";
          return area;
        },
        // 获取长度
        formatLength(line) {
          let dis = 0;
          for (let i = 0; i < line.length - 1; i++) {
            let start = line[i];
            let end = line[i + 1];
            dis += L.latLng([start.lat, start.lng]).distanceTo([
              end.lat,
              end.lng,
            ]); //计算两个点之间的距离，并累加
          }
          //结果得到的也是number类型，单位是 米
          return (dis / 10e2).toFixed(2) + "km";
        },
        drawDeletedBack(e) {
          console.log(e);
          this.map.removeLayer(this.marker);
        },
        //清除绘制
        stopDraw() {
          // 删除全部绘制的图层
          if (this.drawLayerGrounp) {
            this.drawLayerGrounp.clearLayers();
          }
          this.map.removeLayer(this.marker);
        },
        selegeo(_formData) {
          axios({
            // 请求方式
            method: "POST",
            // 请求地址
            url: "https://test-imspipeline.pipechina.com.cn:6080/sjgl-webhd/onlinedata/queryGeoJsonByPoint",
            // url: "http://10.37.99.129:8088/onlinedata/queryGeoJsonByPoint",
            // URL中的查询参数
            data: _formData,
          }).then((res) => {
            if (res.data.code == 10000) {
              this.contentData = res.data.data;
              let _Ddata = res.data.data;
              let layerGeo = L.geoJSON(JSON.parse(_Ddata.geoJson), {
                style: {
                  color: this.showColor,
                  weight: this.showWeight,
                  opacity: 0.5,
                },
              }).addTo(this.highs);
              this.map.fitBounds(layerGeo.getBounds());
            } else {
              this.$message.error("查询失败");
            }
          });
        },
      },
      created() {
        const _data = JSON.parse(
          decodeURIComponent(window.location.href.split("?")[1])
        );
        this.tPipeLineId = _data.tPipeLineId;
        this.pointISLine = _data.pointISLine;
        this.callType = _data.callType;
        if (_data.showWeight) {
          this.showWeight = _data.showWeight;
        }
        if (_data.showColor) {
          this.showColor = _data.showColor;
        }
        if (_data.seeParams) {
          const _formData = new FormData();
          _formData.append("slng", _data.seeParams.slng);
          _formData.append("slat", _data.seeParams.slat);
          _formData.append("elng", _data.seeParams.elng);
          _formData.append("elat", _data.seeParams.elat);
          _formData.append("buffer", "10");
          _formData.append("pipeLineId", this.tPipeLineId);
          this.selegeo(_formData);
        } else {
          if (this.callType) {
            this.editId = _data.editId;
            this.tableName = _data.tableName;
            this.toLocation();
          } else {
            this.editId = this.tPipeLineId;
            this.tableName = "pipeline";
            this.toLocation();
          }
        }
      },
      mounted() {
        this.onLoad();
        // this.addWmsLayer('xzy_prod:pipeline', 'http://47.95.210.199:8081/geoserver/xzy_prod/wms')
        this.addWmsLayer(
          "tgisserver:pipeline",
          "https://test-imspipeline.pipechina.com.cn:6080/sjgl-gisfw/geoserver/tgisserver/wms"
        );
        // this.addWmsLayer('tgisserver:pipeline', 'http://10.37.99.129:8081/geoserver/tgisserver/wms')
        this.initDrawCtrl();
        this.$nextTick(() => {
          this.highlight = new L.FeatureGroup();
          this.map.addLayer(this.highlight);
          const lasso = L.control.lasso();
          this.map.addControl(lasso);
          lasso._container.remove();
          this.map.on("lasso.finished", (event) => {
            alert("showMsg");
            var polygon = L.polygon(event.latLngs, {
              color: "#00c3ff",
              fillColor: "#c4eaf1",
              fillOpacity: 0.6,
            }).addTo(this.drawLayerGrounp);
          });
        });
      },
    });
  </script>
</html>
